import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Req, Request } from '@nestjs/common'
import { UserService } from './user.service'
import { User } from './user.entity'
import { DeleteResult } from 'typeorm'

// controller 的 user 表示用于拦截 user 路径下的所有请求
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('info')
  getUserByToken(@Req() request: Request & { user: { name: string }}): Promise<User | null> {
    // console.log('获取用户信息', request.user)
    return this.userService.findUserByUsername(request.user.name)
  }

  // 获取用户信息
  // @Param('id) 表示直接获取 id 参数
  // ParseIntPipe 表示将 id 参数转换为数字类型
  @Get('/:id')
  getUser(@Param('id', ParseIntPipe) id: number): Promise<User | null> {
    // console.log('🚀 ~ UserController ~ getUser ~ id:', typeof id)
    // 返回用户信息
    return this.userService.findOne(id)
  }

  @Get()
  getAllUser(): Promise<User[]> {
    return this.userService.findAll()
  }

  @Post()
  createUser(@Body() body: User): Promise<User> {
    return this.userService.createUser(body)
  }

  @Delete('/:id')
  deleteUser(@Param('id', ParseIntPipe) id: number): Promise<DeleteResult> {
    return this.userService.deleteUser(id)
  }
}
